package org.example.controller;

import org.example.api.IUserService;
import org.example.api.entity.User;
import org.example.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Re
 * @Date: 2021/4/17 23:45
 */
@WebServlet("/addUser")
public class AddUserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 防止乱码
        resp.setContentType("text/html;utf-8");
        req.setCharacterEncoding("UTF-8");
        // 从表单里取值
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String sex = req.getParameter("sex");
        if (userName==null || "".equals(userName)) {
            req.setAttribute("msg","用户名不能为空");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
            return;
        }
        if (userPassword==null || "".equals(userPassword)) {
            req.setAttribute("msg","密码不能为空");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
            return;
        }
        if (sex ==null || "".equals(sex)) {
            req.setAttribute("msg","请选择性别");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
            return;
        }
        User user = new User(userName,userPassword,sex);
        IUserService iUserService = new UserServiceImpl();
        if (iUserService.checkUser(user) != null){
            req.setAttribute("msg","用户名已存在");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
            return;
        }
        if (iUserService.addUser(user)){
            req.setAttribute("msg","注册成功");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
        } else {
            req.setAttribute("msg","注册失败");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
        }
    }
}
